package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dao.Category;
import com.itheima.dao.Dish;
import com.itheima.dao.Setmeal;
import com.itheima.dao.SetmealDish;
import com.itheima.dto.DishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 套餐管理
 * */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     * */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true )
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("套餐信息:{}",setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     * */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name != null,Setmeal::getName,name);
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo, lambdaQueryWrapper);

        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 删除套餐
     * */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true )
    public R<String> delete(String ids){
        String[] split = ids.split(",");
        List<Long> idlist = Arrays.stream(split).map((item) -> Long.parseLong(item)).collect(Collectors.toList());

        for (int i= 0;i < idlist.size();i++){
            if (setmealService.getById(idlist.get(i)).getStatus() != 1){
                setmealService.removeById(idlist.get(i));
                LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper =new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(SetmealDish::getSetmealId,idlist.get(i));
                setmealDishService.remove(lambdaQueryWrapper);
            }else {
                return R.error("正在售卖中，无法删除");
            }
        }
        return R.success("成功");
    }

    /**
     * 停售
     * */
    @PostMapping("/status/{st}")
    @CacheEvict(value = "setmealCache",allEntries = true )
    public R<String> status(@PathVariable int st,String ids){
        String[] split = ids.split(",");
        List<Long> idlist = Arrays.stream(split).map((item) -> Long.parseLong(item)).collect(Collectors.toList());

        List<Setmeal> collect = idlist.stream().map((item) -> {
            Setmeal setmeal = new Setmeal();
            setmeal.setStatus(st);
            setmeal.setId(item);
            return setmeal;
        }).collect(Collectors.toList());

        setmealService.updateBatchById(collect);
        return R.success("停售/起售 成功");
    }

    /**
     * 根据id查询套餐信息和对应的口味信息
     * */
    @GetMapping("/{id}")
    //@Cacheable(value = "setmealCache",key ="id",unless = "#id == null ")
    public R<SetmealDto> get(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.getWithDishes(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     * */
    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true )
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateWithDishes(setmealDto);
        return R.success("修改成功");
    }

    /**
     * 根据条件查询套餐数据
     * */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        lambdaQueryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(lambdaQueryWrapper);
        return R.success(list);
    }



}
